package com.example.dc.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.dc.utils.JWTUtils;
import com.example.dc.utils.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class Filter implements jakarta.servlet.Filter {

    @Autowired
    private JWTUtils jwtUtils;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException{

        System.out.println("init 初始化方法执行了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse res=(HttpServletResponse) servletResponse;

        //获取请求路径url
        String url=req.getRequestURI();

        //登录操作则放行
        if(url.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);//放行
            return;
        }

        //获取请求路径的令牌
        String token=req.getHeader("token");

        //判断令牌是否存在，不存在，则返回未登录信息
        if(token==null || token==""){
            //转为json
            String notLogin= JSONObject.toJSONString(Result.error("NOT_LOGIN"));
            res.getWriter().write(notLogin);
            return;
        }

        //解析token
        try{
            jwtUtils.parseToken(token);
        }
        catch (Exception err){
            String notLogin= JSONObject.toJSONString(Result.error("NOT_LOGIN"));
            res.getWriter().write(notLogin);
            return;
        }

        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        jakarta.servlet.Filter.super.destroy();

    }

}
